
var http = require('http').createServer(handler);
var io = require('socket.io')(http);
var queryString = require('querystring');

var clients = new Array();

http.listen(3000);

// Handle RESTful API
function handler(req, res) {
    console.log('request = ' + req.url);
    var request = require('url').parse(req.url);
    var body = JSON.stringify({server:'OK'});

    if (request.pathname == '/picture') { // Push picture command.
        var queries = queryString.parse(request.query);
        var clientId = queries['clientId'];
        var address = queries['address'];
        var clientSocket = clients[clientId];

        if (clientSocket != undefined && address != undefined) {
            console.log("sent picture command to " + clientId);
            clientSocket.emit('picture', address);
        }
    }

    res.writeHead(200, {
        'Content-Length': body.length,
        'Content-Type': 'application/json'});
    res.write(body);
    res.end();
}

io.sockets.on('connection', function(socket) {
    console.log('connection established');

    // Receive login event, and save client id with socket id.
    socket.on('login', function(clientId) {
        clients[clientId] = socket;
    });

    socket.on('disconnect', function(data) {
        for (var clientId in clients) {
            if (clients[clientId] == socket) {
                console.log('disconnect from ' + clientId);
                delete clients[clientId];
                break;
            }
        }
    });
});